<template>
  <div class="page-list-live">
    <PageList>
      <template #header>轨迹回放</template>
      <template #filter>
        <ListFilter :form="topFilter" style="z-index: 10;" :lath="'140px'" @search="handleSearch" @reset="handleReset"></ListFilter>
      </template>
      <template #tips>
        <div class="tips">
          <el-button type="primary" style="z-index: 10;" icon="el-icon-video-play" @click="time">播放</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-video-pause" @click="suspendHandler">暂停</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-circle-close" @click="stopHandler">停止</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-refresh" @click="resetPlayHandler">重新播放</el-button>
        </div>
      </template>
      <template #table>
        <div>
          <div>
            总时长(秒)：
            <el-input v-model="duration" style="width: 300px; z-index: 10;" :disabled="clickSwaitch" type="number" @change="timeValueHandler"></el-input>
            最大不能超过 {{ listAry.length }} 秒
          </div>
          <el-slider id="slider" ref="slider" v-model="value" style="z-index: 10;" :show-tooltip="false"></el-slider>
          <div class="divOne">
            <img v-if="imgSrc" class="mapImg" :src="imgSrc" alt />
            <!-- 基站覆盖范围 -->
            <template v-for="item in baseStationList">
              <div
                v-if="listSwitch"
                :key="item.id"
                :style="{ width: item.maxDist + 'px', height: item.maxDist + 'px', left: item.x - (item.maxDist / 2) + 'px', top: item.y - (item.maxDist / 2) + 'px' }"
                class="range"
              >
                <!-- 基站位置 -->
                <!-- <div
                  :style="{ left: (item.maxDist / 2) + 'px', top: (item.maxDist / 2) + 'px' }"
                  :title="`基站名称: ${item.name}; 区域: ${item.scro}; 坐标X: ${item.x}; 坐标Y: ${item.y}; 基站类型: ${item.jztype === 1 ? '进基站' : item.jztype === 2 ? '出基站' : '其他基站' }; 是否是考勤机站: ${item.status ? '是': '否'}`"
                  class="up"
                >
                  <img :src="item.url" alt="基站" />
                </div>-->
                <el-popover placement="top-start" class="up" :style="{ left: (item.maxDist / 2) + 'px', top: (item.maxDist / 2) + 'px' }" trigger="hover">
                  <div class="labelDiv">
                    <span class="shallow">基站名称:</span>
                    <span class="deep">{{ item.name }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">区域:</span>
                    <span class="deep">{{ item.scro }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">基站类型:</span>
                    <span class="deep">{{ item.jztype === 1 ? '进基站' : item.jztype === 2 ? '出基站' : '其他基站' }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">是否是考勤机站:</span>
                    <span class="deep">{{ item.status ? '是': '否' }}</span>
                  </div>
                  <img slot="reference" :src="item.url" alt="基站" />
                </el-popover>
                <!-- 施工队员位置 -->
                <el-popover
                  v-if="prople.deviceId === item.deviceId"
                  placement="top-start"
                  class="people"
                  :style="{ left: item.x - (item.maxDist / 2) < 0 ? (item.maxDist / 2) + prople.left + 'px' : item.x + item.maxDist < 828 ? (item.maxDist / 2) + prople.left + 'px' : prople.left > (item.maxDist / 2) ? prople.left - (item.maxDist / 2) + 'px' : prople.left + 'px', top: item.y - (item.maxDist / 2) < 0 ? (item.maxDist / 2) + prople.top + 'px' : item.y + item.maxDist < 617 ? prople.top + 'px' : prople.top > (item.maxDist / 2) ? prople.top - (item.maxDist / 2) + 'px' : prople.top + 'px' }"
                  trigger="hover"
                >
                  <div class="labelDiv">
                    <span class="shallow">名称:</span>
                    <span class="deep">{{ prople.name }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">RFID卡:</span>
                    <span class="deep">{{ prople.rfid }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">联系方式:</span>
                    <span class="deep">{{ prople.phone }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">是否在职:</span>
                    <span class="deep">{{ prople.status ? '是' : '否' }}</span>
                  </div>
                  <div v-if="prople.plateNumber" class="labelDiv">
                    <span class="shallow">车牌号:</span>
                    <span class="deep">{{ prople.plateNumber }}</span>
                  </div>
                  <img slot="reference" :src="prople.url" alt="施工队员" />
                </el-popover>
              </div>
            </template>
          </div>
        </div>
      </template>
    </PageList>
  </div>
</template>
<script>
  import { assetsImages } from '@/utils/images'
  import listMixin from '@/mixins/list'
  import ListFilter from '@/components/ListFilter'
  import { path, baseStation, tunnel, parameter } from '@/api/api'
  export default {
    components: { ListFilter },
    mixins: [listMixin],
    data() {
      return {
        listSwitch: false,
        // 获取图片地址
        imgUrl: this.$imgUrl + '/',
        imgSrc: '',
        distArr: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
        prople: {
          deviceId: '',
          top: null
        },
        arr: [],
        // 基站数组
        baseStationList: [],
        // 定时器
        timeID: null,
        // 开关
        sliderSwaitch: false,
        // 开关
        clickSwaitch: false,
        // 总时长(秒)
        duration: 10,
        // 得到一个数据的位置
        flag: 0,
        // 进度条数值
        value: [0, 100],
        // 保存所有位置数据
        listAry: [],
        // 搜索内容
        topFilter: {
          'employee.rfid': { label: '人员RFID', placeholder: '请输入人员RFID' },
          'car.rfid': { label: '车辆RFID', placeholder: '请输入车辆RFID' },
          'employee.accessCardID': { label: '门禁ID', placeholder: '请输入门禁ID' },
          "car.plateNumber": { label: '车牌号', placeholder: '请输入车牌号' },
          'employee.name': { label: '员工姓名', placeholder: '请输入员工姓名' },
          createdTime: { label: '时间', placeholder: '请选择时间', type: 'date', arr: ['createdTime', 'createdTime'] }
        },
        iconData: [
          { name: 'BaseStationImage', value: '', id: null },  // 基站
          { name: 'PeopleImage', value: '', id: null }, // 人员
          { name: 'CarImage', value: '', id: null } // 车辆
        ],
      }
    },
    watch: {
      value: function (newValue, oldValue) {
        if (newValue.push) { return }
        // 每秒走多少
        let item = 100 / this.duration
        // 当前位置的秒数
        let merchant = parseInt(Number(newValue) / parseInt(item))
        // 共有多少条数据
        let len = this.listAry.length
        // 得出每秒走多少条数据
        let distanceNum = Math.ceil(len / this.duration)
        // 得到当前位置
        this.flag = merchant * distanceNum
        if (this.flag >= len) {
          this.flag = len - 1
        }
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]

        if (!obj) { return }
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
      }
    },
    mounted() {
      let that = this
      this.getTunnelData()
      this.getMap()
      // 获取按钮
      let slider = document.querySelector('.el-slider__button-wrapper')
      let runway = document.querySelector('.el-slider__runway')
      runway.onmousedown = function () {
        that.sliderSwaitch = true
      }
      // 鼠标按下事件
      slider.onmousedown = function () {
        that.sliderSwaitch = true
        // 先清除一下定时器的值
        clearInterval(that.timeID)
      }
      // 鼠标放开事件
      window.onmouseup = function (event) {
        // 点击了播放才能播放
        if (that.sliderSwaitch && that.clickSwaitch) {
          that.time()
          that.sliderSwaitch = false
        }
      }
    },
    beforeDestroy() {
      clearInterval(this.timeID)
    },
    methods: {
      // 时间修改
      timeValueHandler(event) {
        if (event > this.listAry.length) {
          this.duration = this.listAry.length
        }
      },
      // 重新播放
      resetPlayHandler() {
        this.value = 0
        this.flag = 0
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
        this.time()
      },
      // 播放
      time() {
        // 点击时打开开关
        this.clickSwaitch = true
        // 进度条每秒走多少
        let secondNumber = Number(100 / this.duration)

        if (this.timeID) {
          // 先清除一下定时器的值
          clearInterval(this.timeID)
          // 再创建一下
          this.timeID = null
        }

        // 开启定时器
        this.timeID = setInterval(() => {
          if (this.value + secondNumber >= 100) {
            // 进度条到最后位置
            this.value = 100
            // 清除定时器
            clearInterval(this.timeID)
            // 关闭开关
            this.clickSwaitch = false
          } else {
            // 进度条进度
            this.value = Number(this.value) + secondNumber
          }
        }, 1000)
      },
      // 暂停
      suspendHandler() {
        clearInterval(this.timeID)
        this.clickSwaitch = false
      },
      // 停止
      stopHandler() {
        clearInterval(this.timeID)
        this.value = 0
        this.flag = 0
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
        this.clickSwaitch = false
      },
      // 生成坐标数组
      getListHandler() {
        this.baseStationList.forEach((item, index) => {
          // 设置一个最小值
          let num = this.distArr[0]

          this.distArr.forEach(edit => {

            if (num < edit) {
              // 循环完毕得到一个最大值
              num = edit
            }

          })
          // maxDist是一个表示基站范围的正方形的边长
          item.maxDist = (num * 10 + 10) * 2

          // 得到需要的信息,保存到基站数据中
          item.arr = this.distArr.map(coordinate => {
            return {
              id: coordinate,
              deviceId: item.deviceId,
              rfid: item.rfid,
              name: item.propleName,
              phone: item.phone,
              status: item.propleStatus,
              left: coordinate * 10,
              top: this.random(0, (num * 10 + 10) * 2),
              url: item.url,
              itemUrl: item.itemUrl,
              plateNumber: item.plateNumber
            }
          })
        })

        // 保存所有位置数据
        this.listAry = []

        // 临时数组      
        let arrList = []
        // 尽量减少重复进入作用域
        let list = this.baseStationList

        for (let i = 0; i < list.length; i++) {
          let arr = list[i].arr
          for (let j = 0; j < arr.length; j++) {
            // 循环得到所有数据
            arrList.push(arr[j])
          }
        }
        // 获取数据
        this.listAry = JSON.parse(JSON.stringify(arrList))

        // 设置进度条长度（进度条长度最大可能只能到100）
        this.value = 0

        // 得到下一秒的数据
        let obj = this.listAry[0]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          top: obj.top,
          left: obj.left,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
      },
      // 取随机数
      random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
      },
      // 获取图标
      async getTunnelData() {
        try {
          let response = await Promise.allSettled([
            parameter('get', { parameterName: 'BaseStationImage' }),
            parameter('get', { parameterName: 'CarImage' }),
            parameter('get', { parameterName: 'PeopleImage' })
          ])

          response.forEach(item => {
            this.iconData.forEach(edit => {
              let obj = item.value.data
              if (edit.name === obj.name) {
                edit.value = obj.value
                edit.id = obj.id
              }
            })
          })
        } catch (err) {
          console.log(err)
        }
      },
      // 请求列表数据
      async getList(query) {
        if (query && query.search.length > 0) {
          this.listSwitch = true
        } else {
          this.listSwitch = false
          return
        }
        this.tableLoading = true
        let that = this
        try {
          const { data: { items: resData, count, pageIndex } } = await path('post', query, false)
          if (resData.length === 0) { return this.$message.warning('未查到该员工轨迹记录！') }
          let ary = []
          ary = resData.map(item => {
            return {
              name: item.baseStation.name,
              scro: item.baseStation.area.name,
              jztype: item.baseStation.siteType,
              status: item.baseStation.isForWorkCheck,
              x: item.baseStation.xPosition,
              y: item.baseStation.yPosition,
              deviceId: item.baseStation.deviceId,
              rfid: item.carId ? item.car.rfid : item.employee.rfid,
              plateNumber: item.carId ? item.car.plateNumber : item.employee.plateNumber,
              propleName: item.carId ? item.car.carType : item.employee.name,
              phone: item.carId ? item.car.responsiblePhone : item.employee.phone,
              propleStatus: item.carId ? 1 : item.employee.status,
              url: that.iconData[0].value,
              itemUrl: item.carId ? that.iconData[2].value : that.iconData[1].value,
              maxDist: '',
              arr: []
            }
          })
          this.baseStationList = JSON.parse(JSON.stringify(ary))
          this.getListHandler()
        } catch (err) {
          this.tableLoading = false
          console.error('getList err: ', err)
        }
      },
      // 请求地图
      async getMap() {
        try {
          let obj = { id: 1 }
          let res = await tunnel('get', obj, true)
          if (res.code === 200) {
            if (res.data.backedImageName) {
              this.imgSrc = this.imgUrl + res.data.backedImageName
            } else {
              if (res.data.templateName === '单洞') {
                this.imgSrc = assetsImages.singleHole
              } else if (res.data.templateName === '双洞') {
                this.imgSrc = assetsImages.doubleHole
              }
            }
          }
        } catch (err) {
          console.log(err)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .labelDiv {
    display: flex;
    .deep {
      color: #000;
      width: 120px;
      text-align: left;
    }
    .shallow {
      padding-right: 10px;
      color: #666;
      width: 70px;
      text-align: right;
    }
  }
  .sc-list-filter-col {
    width: auto;
  }
  .tips {
    display: flex;
    padding-bottom: 20px;
  }
  .divOne {
    margin: 0 auto;
    width: 830px;
    height: 619px;
    display: flex;
    position: relative;
    border: 1px solid #ccc;
    background-color: #ccc;
    .mapImg {
      width: 100%;
      height: 100%;
    }
    .range {
      display: inline-block;
      position: absolute;
      // border: 1px solid lime;
      .up {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        position: absolute;
        display: inline-block;
        background-color: #fff;
        transform: translate(-50%, -50%);
        img {
          float: left;
          width: 100%;
          height: 100%;
        }
        // transform: rotateX(120deg) translateZ(220px) translateX(364PX);
        // .baseStation {
        // width: 60px;
        // height: 50px;
        // text-align: center;
        // line-height: 50px;
        // position: absolute;
        // background-color: #53868B;
        // transform: rotateX(180deg);
        // }
      }
      .people {
        width: 20px;
        height: 20px;
        position: absolute;
        border-radius: 50%;
        background-color: #fff;
        display: inline-block;
        transform: translate(-50%, -50%);
        img {
          width: 100%;
          height: 100%;
          float: left;
        }
      }
    }
  }
</style>
